package com.bwie.orders.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.util.UuidUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.bwie.orders.conf.AlipayConfig;
import com.bwie.orders.conf.JwtUtil;
import com.bwie.orders.conf.MD5Util;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.bwie.orders.entity.OrderEntity;
import com.bwie.orders.service.OrderService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author ShuangzhiZhao
 * @email 466505908@qq.com
 * @date 2022-02-22 10:59:44
 */
@Controller
@RequestMapping("orders/order")
public class OrderController {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("1", "2");
        strings.forEach(System.out::println);//新方式打印
        //获取cpu的核数
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedissonClient client;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    //支付
    @RequestMapping("/payment")
    @ResponseBody
    public String payment(@RequestParam Long oid) throws Exception {
        OrderEntity orderEntity = orderService.getById(oid);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderEntity.getOrderno().getBytes(),"UTF-8");
        //付款金额，必填
        String total_amount = new String(orderEntity.getGoodsPrice().toString().getBytes(),"UTF-8");
        //订单名称，必填
        String subject = new String(orderEntity.getGoodsName().getBytes(),"UTF-8");
        //商品描述，可空
        String body = new String(orderEntity.getGoodsName().getBytes(),"UTF-8");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出
        return result;
    }

    @RequestMapping("/success.html")
    public String success(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        R r=orderService.updateOder(params);
        if (r.getCode()==0){
            return "redirect:http://127.0.0.1:5500/activity_list.html";
        }


       return "error";

    }



    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{oid}")
    @ResponseBody
    public R info(@PathVariable("oid") Long oid){
		OrderEntity order = orderService.getById(oid);

        return R.ok().put("order", order);
    }
    /**
     * 回显前台订单页面 去支付
     */
    @RequestMapping("/info/{userId}/{activityId}")
    @ResponseBody
    public R info(@PathVariable("userId") Long userId,
                  @PathVariable("activityId")Long activityId){
        OrderEntity order = orderService.getByUidAid(userId,activityId);

        return R.ok().put("order", order);
    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody OrderEntity order){
		orderService.save(order);

        return R.ok();
    }


    /**
     * 接口地址随机化(隐藏)
     */
    @RequestMapping("/getPath")
    @ResponseBody
    public R getPath(
            HttpServletRequest request,
            @RequestParam("goodsId")Long goodsId,
            @RequestParam("userId")Long userId
    ){
        RLock lock = client.getLock("fangshua");
        try {
            lock.lock();
            //接口防刷 限制访问次数
            String uri = request.getRequestURI();
            String key=uri+"_"+userId;
            Integer count = (Integer) redisTemplate.opsForValue().get(key);
            if (count==null){
                redisTemplate.opsForValue().set(key,1,30,TimeUnit.SECONDS);

            }else if (count<5){
                redisTemplate.opsForValue().set(key,count+1);
            }else {
                return R.error("访问次数过多");
            }
        }finally {
            lock.unlock();
        }
        //随机生成一个pathId 返回给前端
        String str = UuidUtils.generateUuid();
        String pathId= MD5Util.md5(str);
        redisTemplate.boundHashOps("path").put(goodsId+"pathId",pathId);
        redisTemplate.expire("path",60, TimeUnit.SECONDS);
        return R.ok().put("pathId",pathId);
    }




    /**
     * 生成秒杀订单
     */
    @RequestMapping("/{pathId}/msAdd")
    @ResponseBody
    public R msAdd(HttpServletRequest request,
            @PathVariable("pathId")String pathId,
            @RequestParam("userId")Long userId,
                   @RequestParam("activityId")Long activityId,
                   @RequestParam("goodsId")Long goodId
                   ) {

        //去缓存中查询 接口地址
        String path = (String) redisTemplate.boundHashOps("path").get(goodId + "pathId");
        //如果缓存中有，并且传入的地址和缓存中一样则生成订单
        if (StringUtils.isNotEmpty(path)&& path.equals(pathId)) {
            return orderService.msAdd(userId, activityId);
        } else {
            return R.error("非法请求");
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody OrderEntity order){
		orderService.updateById(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] oids){
		orderService.removeByIds(Arrays.asList(oids));

        return R.ok();
    }


}
